<template>
    <fieldset>
        <legend>登入页</legend>
        用户名:
        <input type="text" v-model="username">
        <br>
        密码:
        <input type="password" v-model="password" @keydown.enter="submit">
        <br>
        <button @click="submit">登入</button>
    </fieldset>
</template>
<script setup>
import { ref } from "vue"

//引入请求登入的方法

import { loginApi } from "../../api/users"

//引入users的store

import useUser from "../../store/users"

//引入组合式的路由api

import { useRouter } from "vue-router"

//路由对象
let router = useRouter()

//store对象
let userStore = useUser()

//定义用户名和用户密码的响应式变量

let username = ref("")

let password = ref("")

//登入方法

let submit = async () => {
    // console.log(username.value)
    // console.log(password.value)

    try {
        let res = await loginApi(username.value, password.value)

        //成功登入
        if (res.state) {
            // console.log(res)
            //将用户信息存储到pinia
            userStore.userInfo.value = res.userInfo;
            //将token存到本地
            sessionStorage.setItem('tk', res.token)
            //登入成功要跳转到首页
            router.push('/')
        } else {
            alert(res.msg)
        }

    } catch (e) {
        console.log(e.toString())
    }
}
</script>